<?php
/* config file for general configs */
require_once("../config.php");

/* use the database for queries */
require_once("../class/database.class.php");

/* blog class for site ident */
require_once("../class/blog.class.php");

/* create an instance of the blog */
$b = new blog($_SERVER["HTTP_HOST"]);

/* make sure the correct data is provided */
if(array_key_exists("url", $_GET)==true 
	&& array_key_exists("pass", $_GET)==true){
	// make sure the pass equals the db pass
	if($_GET["pass"]==CONFIG_DB_PASS){		
		// finally everything is fine
		$xml = simplexml_load_string(file_get_contents($_GET["url"])
								,"SimpleXMLElement", LIBXML_NOCDATA);
		// first of all iterate through all categories and add them
		for($c=0;$c<count($xml->category);$c++){
			// add the category to the database
			$b->db->addCategory($xml->category[$c]->name, 
				$xml->category[$c]->url, $xml->category[$c]->body);
		}
		
		// iterate through all articles and add them
		for($a=0;$a<count($xml->article);$a++){
			// get the username of the author 
			$authorUser = $b->db->getUserByName($xml->article[$a]->author->firstname, 
											$xml->article[$a]->author->lastname);
			
			// define image url, filename and download it								
			$imageUrl = $xml->article[$a]->image->attributes()->url;
			$imageFilename = substr($imageUrl,strrpos($imageUrl,"/")+1);
			if(strlen($imageFilename)>0){
				$fullFilename = CONFIG_IMAGE_PATH."/".$imageFilename;
				if(file_exists($fullFilename)){
					// download the file to the local destination
					file_put_contents($fullFilename, file_get_contents($imageUrl));
				}
			}
								
			if(strlen($authorUser)>0){
				$ts = intval($xml->article[$a]->date->attributes()->timestamp);
				// first add the article to the database overwriting existing ones
				$b->db->addArticle($xml->article[$a]->title, $xml->article[$a]->url, 
						$xml->article[$a]->keyword, $xml->article[$a]->content, 
						$authorUser, true, $ts, $imageFilename);
				// next add the category associations
				for($c=0;$c<count($xml->article[$a]->categorylist->category);$c++){
					$b->db->addArticleCategory($xml->article[$a]->url, 
							$xml->article[$a]->categorylist->category[$c]->attributes()->url);
				}
			}else{
				echo $xml->article[$a]->title." not imported: author missing locally.<br />";
			}
		}
	}
}
?>